package com.weike.bsp.pojo.vo

import com.fasterxml.jackson.annotation.JsonInclude
import com.weike.bsp.security.authentication.jwt.JwtAuthenticationToken
import org.springframework.security.core.Authentication

/**
 * 用户登录成功后返回给用户的信息
 */
class LoginUserVO(
        @get:JsonInclude(JsonInclude.Include.NON_NULL)
        var token: String? = null,
        var userId: Long? = null,
        var username: String? = null,
        var name: String? = null,
        var avatar: String? = null,
        var introduction: String? = null,
        var roles: Set<String>? = null,
        @get:JsonInclude(JsonInclude.Include.NON_EMPTY)
        var authorities: Set<String>? = null
) {

    companion object {

        @kotlin.jvm.JvmStatic
        fun from(authentication: Authentication): LoginUserVO {
            val vo = LoginUserVO()
            vo.name = authentication.name
            vo.username = authentication.name

            val roles = HashSet<String>()
            roles.addAll(authentication.authorities.map { it.authority.toLowerCase() }.toSet())

            if (authentication is JwtAuthenticationToken) {
                val at = authentication.accessToken
                if (at != null) {
                    vo.token = at.token
                    vo.userId = at.userId
                }
            }
//            if (authentication is UsernamePasswordAuthenticationToken) {
//                val o = authentication.principal
//                if (o is UserDetailsInfo) {
//                    roles.addAll(o.user.roles.map { it.roleKey.toLowerCase() }.toSet())
//                    vo.avatar = o.user.avatar
//                    vo.introduction = o.user.description
//                }
//            }
//            vo.roles = roles
            return vo
        }
    }

    override fun toString(): String {
        return "LoginUserVO(token=$token, userId=$userId, username=$username, name=$name, avatar=$avatar, introduction=$introduction, roles=$roles, authorities=$authorities)"
    }
}
